﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Domain;
using MediatR;


namespace Casamiel.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class CancelOrderMemberCouponCommandHandler : INotificationHandler<CancelOrderMemberCouponCommand>
	{
		private readonly IOrderService _orderService;
		private readonly IMemberCouponRepository _memberCouponRepository;

		public CancelOrderMemberCouponCommandHandler(IOrderService orderService, IMemberCouponRepository memberCouponRepository)
		{
			_orderService = orderService;
			_memberCouponRepository = memberCouponRepository;
		}

		public async Task Handle(CancelOrderMemberCouponCommand notification, CancellationToken cancellationToken)
		{
			if (notification is null) {
				throw new ArgumentNullException(nameof(notification));
			}

			var order = await _orderService.GetByOrderCodeAsync<ICasaMielSession>(notification.OrderCode).ConfigureAwait(false);
			if (order != null) {
				var discountlist = await _orderService.GetListByOrderBaseId<ICasaMielSession>(order.OrderBaseId).ConfigureAwait(false);
				if (discountlist != null && discountlist.Any()) {
					var count = discountlist.Count;
					for (int i = 0; i < count; i++) {
						if (discountlist[i].DiscountCouponType == 2) {
							var coupon = await _memberCouponRepository.GetKeyAsync<ICasaMielSession>(discountlist[0].DiscountCouponId).ConfigureAwait(false);
							if (coupon != null) {
								coupon.State = 3;
								await _memberCouponRepository.UpdateAsync<ICasaMielSession>(coupon).ConfigureAwait(false);

							}
						}
					}
				}
			}
		}
	}
}
